#ifndef __GENERATOR_H__
#define __GENERATOR_H__
#include "dlx_solver.h"
#include <time.h>
#include <stdlib.h> //for srand() rand()
class generator
{
private:
	Puzzle *pz;
public:
	generator()
	{
		srand((unsigned int)time(0));
		pz=new Puzzle();
	}
	string do_dlx_generator()
	{
		string str;
		dlx_solver ds ;
		int remove[81] ;
		memset(remove,0,sizeof(remove));
		for (int i = 0; i < 81; ++i)
		{
			remove[i] = i;
		}
		for (int i = 0; i < 81; ++i)
		{
			int ri = rand()%81;
			if (ri != i)
			{
				int t = remove[ri];
				remove[ri] = remove[i];
				remove[i] = t;
			}
		}
		while (true)
		{
			pz->clear();
			for (int i =  0 ; i < 17; ++i)//可以认为17个数必然有解，最少初始数的数独题也有17+的数字
			{
				int x = remove[i] / 9;
				int y = remove[i] % 9;
				Point p(x+1,y+1);
				vector<ICandidate*> cands = pz->getCell( p )->getCandidates();
				pz->setNumber(p,cands[rand() % cands.size() ]->getValue());
			}
			str=ds.do_solve(pz->exportPuzzle());
			if (ds.solution_count(pz->exportPuzzle())>0)
				break;
		}
		pz->loadPuzzle(str.c_str());
		//TODO:这里应该直接修改字符串即可，不需要再去用Puzzle对象重组字符串了，不过由于数量级并不是很大，这个优化在非批量操作里是没有必要的
		for (int i = 0; i < 81; ++i)
		{
			int x = remove[i] / 9 + 1 ;
			int y = remove[i] % 9 + 1 ;
			Point p(x,y);
			int num = pz->getNumber(p);
			pz->setNumber(p,0);
			ds.do_solve(pz->exportPuzzle());
			if (ds.solution_count(pz->exportPuzzle()) != 1)
			{
				pz->setNumber(p,num);
			}
		}
		return pz->exportPuzzle();
	}
};
#endif

